#include "assglOpengl.h"

#include <iostream>
// GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

// #include <FreeImage.h>

#include "assglUtils.h"
// #include "Shader.h"


// #define TESTPATH "../../src/sources/"
#define TESTPATH ""

#if 0
EXTERN_C int openglInit(AssglLib *lib)
{
	// Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    lib->GlParamS.Window = glfwCreateWindow(lib->PlayResX, lib->PlayResY, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(lib->GlParamS.Window);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (err != GLEW_OK){
        std::cout << "err:" << err << std::endl;
        exit(1);           // or handle the error in a nicer way
    }
        
    if (!GLEW_VERSION_2_1){ // check that the machine supports the 2.1 API.
        std::cout << "err:version"  << std::endl;
        exit(1);           // or handle the error in a nicer way
    } 
        
    // Define the viewport dimensions
    glViewport(0, 0, lib->PlayResX, lib->PlayResY);

    // Set OpenGL options
    glEnable(GL_CULL_FACE);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Compile and setup the shader
	lib->GlParamS.Program = Shader(std::string(std::string(TESTPATH) + "vertexShaderSource.vs").c_str(),
									   std::string(std::string(TESTPATH) + "fragmentShaderSource.fs").c_str());
	glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(lib->PlayResX), 0.0f, static_cast<GLfloat>(lib->PlayResY));
    // lib->GlParamS.ShaderP->Use();
    glUniformMatrix4fv(glGetUniformLocation(lib->GlParamS.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));

	return 0;
}

void RenderText1(AssglLib *lib,FT_Face &face,const wchar_t* text, int size)
{
    for (int i = 0; i < size; i++) {
        //int index =  FT_Get_Char_Index(face,unicodeArr[i]);
        std::cout << "text[" + std::to_string(i)+ "]:" << text[i] <<std::endl;
        if (FT_Load_Char(face, text[i], FT_LOAD_RENDER))
        {
            // LOGCATE("TextRenderSample::LoadFacesByUnicode FREETYTPE: Failed to load Glyph");
            std::cout << "error TextRenderSample::LoadFacesByUnicode FREETYTPE: Failed to load Glyph" << std::endl;
            continue;
        }
        // 字形大小
		int font_width = face->glyph->bitmap.width;
		int font_rows = face->glyph->bitmap.rows;
		// 从基准线到字形左部/顶部的偏移值
		int font_left = face->glyph->bitmap_left;
		int font_top  = face->glyph->bitmap_top;
		// 原点距下一个字形原点的距离
		int font_x = face->glyph->advance.x;
		//
		unsigned char* data = face->glyph->bitmap.buffer;

        // Generate texture
        GLuint texture;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(
                GL_TEXTURE_2D,
                0,
                GL_RED,
                font_width,
                font_rows,
                0,
                GL_RED,
                GL_UNSIGNED_BYTE,
                data
        );

        // Set texture options
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        // Now store character for later use
        Character character = {
                texture,
                // glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
                face->glyph->bitmap.width, 
                face->glyph->bitmap.rows,
                // glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
                face->glyph->bitmap_left, 
                face->glyph->bitmap_top,
                // static_cast<GLuint>((face->glyph->advance.x / MAX_SHORT_VALUE) << 6)
                face->glyph->advance.x            
        };
        // lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Characters.insert(std::pair<wchar_t, Character>(text[i], character));

        // std::map<wchar_t, Character> CharactersTmp = lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Characters;
        // CharactersTmp.insert(std::pair<wchar_t, Character>(text[i], character));
        // lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Characters = CharactersTmp;

        Character CharactersTmp = lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Characters[i];
        CharactersTmp = character;
        lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Characters[i] = CharactersTmp;
    }
}

void RenderText2(AssglLib *lib,const wchar_t *text,
                 int textLen, GLfloat x, GLfloat y, GLfloat scale,
                 glm::vec3 color, glm::vec2 viewport)
{

    for (int i = 0; i < textLen; i++)
    {
        Character ch = lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Characters[i];

        GLfloat xpos = x + ch.BearingX * scale;
        GLfloat ypos = y - (ch.SizeY - ch.BearingY) * scale;

        GLfloat w = ch.SizeX * scale;
        GLfloat h = ch.SizeY * scale;

        // 当前字符的VBO
        GLfloat vertices[6][8] = {
                { xpos,     ypos + h,   0.0, 1.0f, 0.0f, 0.0f , 0.0f, 0.0f },
                { xpos,     ypos,       0.0, 0.0f, 1.0f, 0.0f , 0.0f, 1.0f },
                { xpos + w, ypos,       1.0, 0.0f, 0.0f, 1.0f , 1.0f, 1.0f },

                { xpos,     ypos + h,   0.0, 1.0f, 0.0f, 0.0f , 0.0f, 0.0f },
                { xpos + w, ypos,       1.0, 0.0f, 1.0f, 0.0f , 1.0f, 1.0f },
                { xpos + w, ypos + h,   1.0, 0.0f, 0.0f, 1.0f , 1.0f, 0.0f }
        };

        // 在方块上绘制字形纹理
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, ch.TextureID);
        // glUniform1i(m_SamplerLoc, 0);

        // 更新当前字符的VBO
        glBindBuffer(GL_ARRAY_BUFFER, lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.VBO);
        glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
        // glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) * 6, &vertices[0][0], GL_STATIC_DRAW);

        glBindVertexArray(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.VAO);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), 0);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
        glEnableVertexAttribArray(2);

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        // 绘制方块
        glDrawArrays(GL_TRIANGLES, 0, 6);
         
        // 更新位置到下一个字形的原点，注意单位是1/64像素
        x += (ch.Advance >> 6) * scale; //(2^6 = 64)
    }
    
    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_2D, 0);
}

int openglTextInit(AssglLib *lib)
{
	// FreeType
    // FT_Library ft;
    // All functions return a value different than 0 whenever an error occurred
    if (FT_Init_FreeType(&(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Ft)))
        std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl;

	// Load font as face
	// FT_Face face;
	if (FT_New_Face(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Ft,
					std::string(std::string(TESTPATH) + lib->AssglTrackItem[lib->AssglTrackCounts].FontName).c_str(), 0,
					&(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Face)))
		std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl;

    FT_Select_Charmap(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Face, FT_ENCODING_UNICODE);//   FT_ENCODING_GB2312  FT_ENCODING_UNICODE

    // Set size to load glyphs as
	FT_Set_Pixel_Sizes(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Face, 0,
					   lib->AssglTrackItem[lib->AssglTrackCounts].FontSize);

	// Disable byte-alignment restriction
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 

    // Load first 128 characters of ASCII set
	wchar_t BYTE_FLOW[LINESUBTITLECOUNTS] = {0};
	char_to_wchar(BYTE_FLOW, lib->AssglTrackItem[lib->AssglTrackCounts].Text);
	// lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Text = BYTE_FLOW;
    int wcharLen = wcslen(BYTE_FLOW);
    wmemcpy(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Text,BYTE_FLOW,wcharLen);
	
    RenderText1(lib,lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Face,BYTE_FLOW, wcharLen);

    glBindTexture(GL_TEXTURE_2D, 0);
    // Destroy FreeType once we're finished
    FT_Done_Face(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Face);
    FT_Done_FreeType(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Ft);

    // Configure VAO/VBO for texture quads
    glGenVertexArrays(1, &(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.VAO));
    glGenBuffers(1, &(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.VBO));

    glBindVertexArray(lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.VAO);
    glBindBuffer(GL_ARRAY_BUFFER, lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 8, NULL, GL_DYNAMIC_DRAW);
    
    glEnableVertexAttribArray(0);
	return 0;
}

#endif

void SaveScreenshotToPicture(const char* filename, int width, int height) {
    // 创建一个缓冲区，用于存储屏幕像素数据
    BYTE* buffer = (BYTE*)malloc( sizeof(BYTE) *width * height * 3);
    glReadBuffer(GL_BACK);
    glReadPixels(0, 0, width, height, GL_BGR_EXT, GL_UNSIGNED_BYTE, buffer);
 
    // 使用FreeImage将像素数据保存为图片
    FIBITMAP* bitmap = FreeImage_ConvertFromRawBits(buffer, width, height, width * 3, 24, 0xFF0000, 0x00FF00, 0x0000FF, false);
    FreeImage_Save(FIF_PNG, bitmap, filename, 0);
 
    FreeImage_Unload(bitmap);
    free(buffer) ;
}

unsigned char* SaveScreenshotToMemory(AssglLib *lib, int width, int height) {
    // unsigned char* memory_buffer = NULL;  
	FIMEMORY * hMemory = NULL ;
    // int buffer_size = 0; 
	// 创建一个缓冲区，用于存储屏幕像素数据
    BYTE* buffer = (BYTE*)malloc( sizeof(BYTE) *width * height * 3);
    glReadBuffer(GL_BACK);
    glReadPixels(0, 0, width, height, GL_BGR_EXT, GL_UNSIGNED_BYTE, buffer);
 
    // 使用FreeImage将像素数据保存为图片
    FIBITMAP* bitmap = FreeImage_ConvertFromRawBits(buffer, width, height, width * 3, 24, 0xFF0000, 0x00FF00, 0x0000FF, false);
    // FreeImage_Save(FIF_PNG, bitmap, "testpngBitmap.png", 0);
	
	hMemory = FreeImage_OpenMemory() ;
	if (FreeImage_SaveToMemory(FIF_PNG, bitmap, hMemory, PNG_DEFAULT) == 0) {  
        printf("Failed to save image to memory.\n");  
        FreeImage_Unload(bitmap);  
        // FreeImage_UnInitialise();  
        return nullptr;  
    }  

    FreeImage_SeekMemory(hMemory, 0, SEEK_END);
    long bufferSize = FreeImage_TellMemory(hMemory);
    
    unsigned char* pngBuffer = new unsigned char[bufferSize];
    unsigned int actualReadCount = bufferSize;
    FreeImage_SeekMemory(hMemory, 0, SEEK_SET);
    FreeImage_ReadMemory(pngBuffer, bufferSize, actualReadCount, hMemory);
    
    {
        //获取图像信息
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage =  (AssglImage*)calloc(0,sizeof(AssglImage));
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->stride = bufferSize;
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->bitmap = (unsigned char*)malloc(sizeof(unsigned char)*bufferSize);
        memcpy(lib->AssglTrackItem[lib->AssglTrackCounts].AImage->bitmap,pngBuffer,bufferSize);
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->w = FreeImage_GetWidth(bitmap);
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->h = FreeImage_GetHeight(bitmap);
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->dst_x = lib->AssglTrackItem[lib->AssglTrackCounts].PosX;
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->dst_y = lib->AssglTrackItem[lib->AssglTrackCounts].PosY;
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->color = FreeImage_GetColorsUsed(bitmap);
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->type = AssglImage::IMAGE_TYPE_CHARACTER;
    }
    
    FreeImage_Unload(bitmap);
    free(buffer) ;
    FreeImage_CloseMemory(hMemory);
    // FreeImage_DeInitialise();

#if 0
    //=======test 1============
    FILE* f = fopen("testpngBitmap1.png", "wb");
    fwrite(pngBuffer, sizeof(char), bufferSize, f);
    fclose(f);
    //=======test 1 end============

    //=======test 2============
    BYTE *mem_buffer = NULL;
    DWORD  size_in_bytes = 0;
    bool bSuccess = FreeImage_AcquireMemory(hMemory, &mem_buffer, &size_in_bytes);
	assert(bSuccess);
    FILE *stream = fopen("testpngBitmap4.yuv", "wb");
    if(stream) {
        fwrite(mem_buffer, sizeof(BYTE), size_in_bytes, stream);
        fclose(stream);
    }
    //=======test 2 end============

    //=======test 3============

    // FIBITMAP* bitmapTest = (FIBITMAP*)malloc(sizeof(FIBITMAP));
    // bitmapTest->data = malloc(sizeof(char)*bufferSize);
    // memcpy(bitmapTest->data,pngBuffer,bufferSize);
    // FreeImage_Save(FIF_PNG, bitmapTest, "testpngBitmap4.png", 0);
    //=======test 3 end============
#endif
	return pngBuffer;
}

unsigned char* SaveScreenshotToMemory_test(AssglLib *lib, int width, int height) {
    // unsigned char* memory_buffer = NULL;  
	FIMEMORY * hMemory = NULL ;
    // int buffer_size = 0; 
	// 创建一个缓冲区，用于存储屏幕像素数据
    BYTE* buffer = (BYTE*)malloc( sizeof(BYTE) *width * height * 3);
    glReadBuffer(GL_BACK);
    glReadPixels(0, 0, width, height, GL_BGR_EXT, GL_UNSIGNED_BYTE, buffer);
 
    // 使用FreeImage将像素数据保存为图片
    FIBITMAP* bitmap = FreeImage_ConvertFromRawBits(buffer, width, height, width * 3, 24, 0xFF0000, 0x00FF00, 0x0000FF, false);
    // FreeImage_Save(FIF_PNG, bitmap, "testpngBitmap.png", 0);
	
	hMemory = FreeImage_OpenMemory() ;
	if (FreeImage_SaveToMemory(FIF_PNG, bitmap, hMemory, PNG_DEFAULT) == 0) {  
        printf("Failed to save image to memory.\n");  
        FreeImage_Unload(bitmap);  
        // FreeImage_UnInitialise();  
        return nullptr;  
    }  

    FreeImage_SeekMemory(hMemory, 0, SEEK_END);
    long bufferSize = FreeImage_TellMemory(hMemory);
    
    unsigned char* pngBuffer = new unsigned char[bufferSize];
    unsigned int actualReadCount = bufferSize;
    FreeImage_SeekMemory(hMemory, 0, SEEK_SET);
    FreeImage_ReadMemory(pngBuffer, bufferSize, actualReadCount, hMemory);
    
    {
        //获取图像信息
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage =  (AssglImage*)calloc(0,sizeof(AssglImage));
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->stride = bufferSize;
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->bitmap = (unsigned char*)malloc(sizeof(unsigned char)*bufferSize);
        memcpy(lib->AssglTrackItem[lib->AssglTrackCounts].AImage->bitmap,pngBuffer,bufferSize);
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->w = FreeImage_GetWidth(bitmap);
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->h = FreeImage_GetHeight(bitmap);
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->dst_x = lib->AssglTrackItem[lib->AssglTrackCounts].PosX;
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->dst_y = lib->AssglTrackItem[lib->AssglTrackCounts].PosY;
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->color = FreeImage_GetColorsUsed(bitmap);
        lib->AssglTrackItem[lib->AssglTrackCounts].AImage->type = AssglImage::IMAGE_TYPE_CHARACTER;
    }
    
    FreeImage_Unload(bitmap);
    free(buffer) ;
    FreeImage_CloseMemory(hMemory);
    // FreeImage_DeInitialise();
    return pngBuffer;
}

unsigned char* openglRender(AssglLib *lib)
{
	// Game loop
    // while (!glfwWindowShouldClose(lib->GlParamS.Window))
    {
        // Check and call events
        glfwPollEvents();

        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        GLfloat timeValue = glfwGetTime();//获取当前的时间（秒）
        // std::cout << "timeValue:" << timeValue << std::endl;
        int elapsedTime = glutGet(GLUT_ELAPSED_TIME); // 获取经过的时间（毫秒）
        // std::cout << "elapsedTime:" << elapsedTime%25 << std::endl;

        // 修改 x y的值，来让文字运动
        // GLfloat  x = static_cast<int>(timeValue * 100) * PI;
        // GLfloat  y = static_cast<int>(timeValue * 100) * PI;

        glm::vec2 point = Bezier2Point(glm::vec2(0,0),glm::vec2(500,30),glm::vec2(300,300));

        GLfloat  x = point.x;
        GLfloat  y = point.y;
        // std::cout << "x:" << x  << "--y:" << y << std::endl;
		const wchar_t *BYTE_FLOW = lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Text;
		// lib->GlParamS.ShaderP->Use();
        glUseProgram(lib->GlParamS.Program); 
        RenderText2(lib,  BYTE_FLOW,wcslen(BYTE_FLOW), 
                 x, y, 1.0f, glm::vec3(0.7, 0.7f, 0.2f), 
                 glm::vec2(1.0,1.0));

        // Swap the buffers
        glfwSwapBuffers(lib->GlParamS.Window);
    }

    unsigned char *memory_buffer = SaveScreenshotToMemory(lib,lib->PlayResX, lib->PlayResY);
    // lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.Buffer = memory_buffer;   


#if 0
    //在这里进行内存拷贝试试？
    AssglImage * aImage =  (AssglImage*)calloc(0,sizeof(AssglImage));
    aImage->bitmap = (unsigned char*)malloc(sizeof(unsigned char)*lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.BufferSize);
    memcpy(aImage->bitmap,memory_buffer,lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.BufferSize);  

    FILE* f = fopen("testpngBitmap2.png", "wb");
    fwrite(lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.Buffer, sizeof(char), lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.BufferSize, f);
    fclose(f);
#endif

    return memory_buffer;
}


void openglRender_test(AssglLib *lib,AVFrame **out)
{
	// Game loop
    // while (!glfwWindowShouldClose(lib->GlParamS.Window))
    {
        // Check and call events
        glfwPollEvents();

        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        GLfloat timeValue = glfwGetTime();//获取当前的时间（秒）
        // std::cout << "timeValue:" << timeValue << std::endl;
        int elapsedTime = glutGet(GLUT_ELAPSED_TIME); // 获取经过的时间（毫秒）
        // std::cout << "elapsedTime:" << elapsedTime%25 << std::endl;

        // 修改 x y的值，来让文字运动
        // GLfloat  x = static_cast<int>(timeValue * 100) * PI;
        // GLfloat  y = static_cast<int>(timeValue * 100) * PI;

        glm::vec2 point = Bezier2Point(glm::vec2(0,0),glm::vec2(500,30),glm::vec2(300,300));

        GLfloat  x = point.x;
        GLfloat  y = point.y;
        // std::cout << "x:" << x  << "--y:" << y << std::endl;
		const wchar_t *BYTE_FLOW = lib->AssglTrackItem[lib->AssglTrackCounts].GlTextParamS.Text;
		// lib->GlParamS.ShaderP->Use();
        glUseProgram(lib->GlParamS.Program); 
        RenderText2(lib,  BYTE_FLOW,wcslen(BYTE_FLOW), 
                 x, y, 1.0f, glm::vec3(0.7, 0.7f, 0.2f), 
                 glm::vec2(1.0,1.0));

        // Swap the buffers
        glfwSwapBuffers(lib->GlParamS.Window);
    }

    glReadPixels(0, 0, lib->PlayResX, lib->PlayResY, lib->PixFmt, GL_UNSIGNED_BYTE, (GLvoid *) (*out)->data[0]);

#if 0
    unsigned char *memory_buffer = SaveScreenshotToMemory(lib,lib->PlayResX, lib->PlayResY);
    // lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.Buffer = memory_buffer;   
#endif

#if 0
    //在这里进行内存拷贝试试？
    AssglImage * aImage =  (AssglImage*)calloc(0,sizeof(AssglImage));
    aImage->bitmap = (unsigned char*)malloc(sizeof(unsigned char)*lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.BufferSize);
    memcpy(aImage->bitmap,memory_buffer,lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.BufferSize);  

    FILE* f = fopen("testpngBitmap2.png", "wb");
    fwrite(lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.Buffer, sizeof(char), lib->AssglTrackItem[lib->AssglTrackCounts].GlPicturePa.BufferSize, f);
    fclose(f);
#endif

    // return memory_buffer;
}